import { useMemberStore } from "@/store/module/member";
import { useTask } from "@/utils/message";

// 设置请求的baseUrl
let baseUrl = "";
// #ifdef H5
baseUrl = import.meta.env.ENV_API_PREFIX; // h5去掉域名，解决跨域问题
// #endif
// #ifndef H5
baseUrl = import.meta.env.ENV_DOMAIN + import.meta.env.ENV_API_PREFIX;
// #endif


// 请求类型
type requestType = "GET" | "POST" | "PUT" | "DELETE";


// 接口返回数据类型
type responseData = {
    code: number;
    data: any;
    msg: string;
};




// 拦截器配置
const httpInterceptor = {
  invoke(options: any) {
        // 1. 非 http 开头需拼接地址
        if (!options.url.startsWith("http")) {
            options.url = baseUrl + options.url;
        }
        // 2. 请求超时
        options.timeout = 100000;
        // 3. 添加请求头
        options.header = {
            Accept: "application/json",
            "Content-Type": "application/json",
            "X-Requested-With": "XMLHttpRequest",
            "Access-Control-Allow-Origin": "*",
            ...options.header,
        };
        // 4. 添加 token 请求头标识
        const token = uni.getStorageSync("token");
        if (token) {
            options.header.token = token;
            options.header.apitoken = token;
        }
    },
};

// 拦截 request 请求
uni.addInterceptor("request", httpInterceptor);


/**
 * 请求函数封装
 * @param url 请求api地址
 * @param method 请求类型
 * @param params 请求参数
 * @returns
 */

export const http = (options: any): Promise<responseData> => {
    // 返回一个新的promise
    return new Promise((resolve, reject) => {
        uni.request({
            //填充拦截器的请求数据
            ...options,
            success: (response: any) => {
                // uni.hideLoading();
                // 根据状态码给予提示和返回对应数据
                const statusCode: number = response.statusCode;
                if (statusCode >= 200 && statusCode < 300) {
                    resolve(response.data);
                } else if (statusCode === 401) {
                    const memberStore = useMemberStore();
                    memberStore.clearUserInfo();
                    uni.navigateTo({ url: "/pages/login/login" });
                    reject(response);
                } else {
                    uni.showToast({
                        icon: "none",
                        title: response.msg || "请求错误",
                    });
                    reject(response);
                }
            },

            fail: (err: any) => {
                // uni.hideLoading();
                uni.showToast({
                    icon: "none",
                    title: "网络错误，换个网络试试",
                });
                reject(err);
            },
        });
    });
};



/**
 * 文件上传函数封装
 * @param url 请求api地址
 * @param method 请求类型
 * @param params 请求参数
 * @param filePath 图片临时路径
 * @returns
 */

// 文件上传
export const useUploadFile = (url: string, method: requestType, params?: any, formData?: any) => {
    return new Promise((resolve, reject) => {
        uni.showLoading({ title: "上传中", mask: false });
        uni.uploadFile({
            url: baseUrl + url,
            filePath: params.filePath,
            name: "image",
            formData: formData ? formData : { user: "test" },
            success: (uploadFileRes: UniApp.UploadFileSuccessCallbackResult) => {
                uni.hideLoading();
                let data = JSON.parse(uploadFileRes.data);
                if (data.code === 200) {
                    return resolve(data.data);
                } else {
                    useTask(data.msg);
                    return reject(data);
                }
            },
            fail: function (err: UniApp.GeneralCallbackResult) {
                uni.hideLoading();
                if (err.errMsg.indexOf("timeout") > -1) {
                    useTask("请求超时");
                }
                if (err.errMsg.indexOf("abort") > -1) {
                    useTask("服务异常");
                }
                return reject(err);
            },
        });
    });
}



